﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Coslen.TahorCRM.Security;

namespace Coslen.TahorCRM.UI.www.Controllers
{
    public class TahorBaseController : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            ViewBag.TahorUser = HttpContext.User as TahorPrincipal;
        }

        #region Process Model / Save / Update Exception Methods

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ex"></param>
        protected void ProcessDbEntityValidationException(DbEntityValidationException ex)
        {
            StringBuilder sbError = new StringBuilder();

            sbError.AppendFormat("<ul>");
            foreach (var item in ex.EntityValidationErrors)
            {
                foreach (var innerError in item.ValidationErrors)
                {
                    sbError.AppendFormat("<li>");
                    sbError.AppendFormat("{0} - {1}", innerError.PropertyName, innerError.ErrorMessage);
                    sbError.AppendFormat("</li>");
                }
            }
            sbError.AppendFormat("</ul>");

            //
            ViewBag.ErrorMessage = sbError.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ex"></param>
        protected void ProcessDbUpdateException(DbUpdateException ex)
        {
            StringBuilder sbError = new StringBuilder();


            foreach (DbEntityEntry dbEntityEntry in ex.Entries)
            {

            }

            sbError.AppendFormat("<ul>");
            int index = 0;
            {
                index++;
                sbError.AppendFormat("<li>");
                Exception sourceEx = GetSourceException(ex);
                sbError.AppendFormat("{0} - {1}", index, sourceEx.Message);
                sbError.AppendFormat("</li>");
            }
            sbError.AppendFormat("</ul>");

            //
            ViewBag.ErrorMessage = sbError.ToString();
        }

        private Exception GetSourceException(Exception ex)
        {
            if (ex.InnerException == null)
            {
                return ex;
            }

            return GetSourceException(ex.InnerException);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ex"></param>
        protected void ProcessSqlException(SqlException ex)
        {
            StringBuilder sbError = new StringBuilder();

            sbError.AppendFormat("<ul>");
            int index = 0;
            foreach (SqlError item in ex.Errors)
            {
                index++;
                sbError.AppendFormat("<li>");
                sbError.AppendFormat("{0} - {1}", index, item.Message);
                sbError.AppendFormat("</li>");
            }
            sbError.AppendFormat("</ul>");

            //
            ViewBag.ErrorMessage = sbError.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ex"></param>
        protected void ProcessException(Exception ex)
        {
            StringBuilder sbError = new StringBuilder();

            sbError.AppendFormat("{0}", ex.Message);
            //
            ViewBag.ErrorMessage = sbError.ToString();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="modelState"></param>
        protected void ProcessModelState(ModelStateDictionary modelState)
        {

            var errorStates = modelState.Values.Where(x => x.Errors.Count >= 1).ToList();

            StringBuilder sbError = new StringBuilder();

            sbError.AppendFormat("<ul>");
            
            int errorNumber = 0;
            foreach (KeyValuePair<string, ModelState> keyValuePair in modelState)
            {
                if (keyValuePair.Value.Errors.Count() >= 1)
                {
                    foreach (var innerError in keyValuePair.Value.Errors)
                    {
                        errorNumber++;
                        sbError.AppendFormat("<li>");
                        sbError.AppendFormat("{0} {2} - {1}", errorNumber, innerError.ErrorMessage, keyValuePair.Key);
                        sbError.AppendFormat("</li>");
                    }
                }
            }

            sbError.AppendFormat("</ul>");

            //
            ViewBag.ErrorMessage = sbError.ToString();
        }

        #endregion 

        public ActionResult RedirectToSource(string source, int currentId)
        {
            string currentAction = ControllerContext.RouteData.Values["action"].ToString();
            string currentController = ControllerContext.RouteData.Values["controller"].ToString(); 

            string[] sourceSegments = source.Split(':');
            string newSource = currentController + ":" + currentAction + ":" + currentId.ToString();
            return RedirectToAction(sourceSegments[1], new { Controller = sourceSegments[0], id = sourceSegments[2], source = newSource });
        }

        public string ConvertSourceToSourceUrl(string source, int currentId)
        {

            string currentAction = string.Empty;
            string currentController = string.Empty;
            string newSource = string.Empty;
            string url = string.Empty;

            if (string.IsNullOrWhiteSpace(source))
            {
                currentAction = "Index";
                currentController = ControllerContext.RouteData.Values["controller"].ToString();
                url = Url.Action(currentAction, new { Controller = currentController });
                return url;
            }

            string[] sourceSegments = source.Split(':');
            currentAction = ControllerContext.RouteData.Values["action"].ToString();
            currentController = ControllerContext.RouteData.Values["controller"].ToString();
            newSource = currentController + ":" + currentAction + ":" + currentId.ToString();
            url = Url.Action(sourceSegments[1], new { Controller = sourceSegments[0], id = sourceSegments[2], source = newSource });
            return url;
        }
    }
}
